<?php
namespace app\web\controller;

use app\model\Theme; 
use app\model\Poster; 
use app\model\Worker as Worker_mod;

class Worker extends Base
{
    public function Worker()
    {
global $_G, $_P;
$system = $_G['system'];
$_G['page']['title'] = '员工列表 - ' . $system['sysname'];
//load_func('tpl');
$GLOBALS['frames'] = array();
$themeid = intval($_P['themeid']);
if($themeid <= 0){
	$themeid = Theme::getDefaultThemenew();
}
$theme = Theme::getThemeById($themeid);
$config = 	Theme::getConfig($themeid);
if(empty($themeid)){
	return_msg('还没有创建活动,请联系管理员');
}
$id = intval($_P['id']);
$do = 'worker';
$op = !empty($_P['op']) ? $_P['op'] : 'display';
$url = createWebUrl($do,array('op' => 'display','themeid'=>$themeid));
$shenfen = array("未完成","超级管理员","商家管理员","员工");
$company_txt = $_P['company'];
$team_txt = $_P['team'];
if($op == 'display' || $op == 'post') {
	if ($system['ruanjian']==3) {
			$compaytxt = "";
			$teamtxt = "";
			$sql = 'SELECT s.id as sid, s.name as companyname FROM ' . tablename ( t_shangjia ) . " as s 
					ORDER BY s.displayorder,s.id ";
			$companylist = db_select($sql);
			foreach ($companylist as $index => $item) {
				$compaytxt .= ",\"" . $item['sid'] . "|" . $item['companyname'] . "\"";
				$sql = 'SELECT t.id as tid, t.name as teamname FROM ' . tablename ( t_team ) . " t
					where company = " . $item['sid'] . " ORDER BY t.id  ";
				$teamlist = db_select($sql);
				$teamtxt .= ",[\"请选择团队\",";
				foreach ($teamlist as $teamindex => $row) {
					$teamtxt .= "\"" . $row['tid'] . "|" . $row['teamname'] . "\",";
				}
				$teamtxt .= "]";
			}
	}else{
			$sql = 'SELECT t.id as tid, t.name as teamname FROM ' . tablename ( t_team ) . " t
					ORDER BY t.id  ";
			$teamlist = db_select($sql);
	}
}
if($op == 'update') {
	if (!empty($_P['workerid'])) {
		$result = Theme::renewworkreport($themeid,intval($_P['workerid']));
	    $gsum12 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
	        WHERE r.themeid ='{$themeid}'  and r.status > 0 and r.status!=3" ));
	    if ($config['joinfee']=='0.00' && $config['groupprice']=='0.00' && $gsum12==0){
	        return_tips($result.'条数据更新，免费报名，成交数为报名数！');
	    }else{
	    	return_tips($result.'条数据更新');
	    }
	}else{
		$page = max ( 1, intval ( $_P['page'] ) );
		$pagesize = 20;
		if ($page==1) {
			Worker_mod::WorkerDeleteChongfu($themeid);
			$gsum12 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
		        WHERE r.themeid ='{$themeid}'  and r.status > 0 and r.status!=3" ));
			if ($config['joinfee']=='0.00' && $config['groupprice']=='0.00' && $gsum12==0){
		        echo ('免费报名，成交数为报名数！<br>');
		    }
		}
		$total = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_worker ) . "
	            WHERE themeid ='{$themeid}'" ));
		echo "正在更新第" . $page . "页/共" .ceil($total / $pagesize) . "页<br>";

		$wlist = db_select('SELECT * FROM ' . tablename(t_worker) . " order by id desc LIMIT " . ($page - 1) * $pagesize . ',' . $pagesize );
	    foreach ($wlist as $index => $item) {
			$result = Theme::renewworkreport($themeid,intval($item['uid']));
			echo "ID:" .$item['uid'] ." 姓名：【" . $item['username'] . "】 更新：" . $result . "条<br>";
		}

	    if ($page *$pagesize < intval($total )){
	        $page = $page+1;
	        $url = 'http://'.$_SERVER['HTTP_HOST']."/web/index.php?c=site&a=entry&op=update&themeid=1&do=worker&m=".MODULE_NAME. "&page=" . $page ;
	        echo "<script language='javascript' type='text/javascript'>";
	        echo "window.location.href='$url';"; 
	        echo "</script>";  
	        exit;
	    }
    }
    exit;
}

if($op == 'post') {
	
	if($id > 0) {
        $poster =  Poster::getByThemeIdnew($themeid,1);
        if(!empty($poster['id'])){
            $isposter=true;
        }else{
            $isposter=false;
        }
		$sql = 'SELECT * FROM ' . tablename(t_worker) . ' 
				WHERE id = :id';

		$sql = 'SELECT w.*,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
			left join " . tablename ( t_team ) . " as t on w.team = t.id
			left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
			WHERE w.id =:id";
		$item = db_find($sql, array( ':id' => $id));

		if(empty($item)) {
			return_tips('不存在或已删除', $url, 'success');
		}
		//load_model('mc');
		if(!checksubmit('submit')) {
			$team_txt = $item['team'] ."|".$item['teamname'];
			$company_txt = $item['company'] ."|".$item['companyname'];
		}
	}
	
	if(checksubmit('submit')) {
		$avatar = tomedia($_P['avatar']);
		// $companyteam= array();
		// if (!empty($_P['companyteam'])){
	 //    	$companyteam=explode(',', $_P['companyteam']);
		// }
		echo $team_txt;
		echo $company_txt;
		if(!empty($team_txt) && $team_txt!="请选择团队"){
			$team=explode('|', $team_txt);
			$condition .= ' and w.team = :teamid';
			$teamval = $team[0];
		}

		if(!empty($company_txt) && $company_txt!="请选择商家"){
			$company=explode('|', $company_txt);
			$companyval = $company[0];
		}

		if (!empty($_P['qrcode'])) {
			$qrcode = tomedia($_P['qrcode']);
		}else{
			$qrcode = $item['qrcode'];
		}
        $qrcode = Poster::base64_image_content($qrcode);
		$data = array(
				'username' => trim($_P['username']),
				'nickname' => trim($_P['nickname']),
                'avatar' => $avatar,
				
				'mobile' => trim($_P['mobile']),
				'level' => intval($_P['level']),
				'qrcode' => $qrcode,
				'company' => $companyval,
				'team' => $teamval,
				);

		if($id >0) {
			db_update(t_worker, $data, array('uid' => $item['uid']));
            if (!empty($qrcode)){
                $alltheme = Theme::getAllTheme();
                if (!empty($alltheme)) {
                    foreach ($alltheme as $key => $row) {
                        //判断是否有设置首图海报，有则直接生成
                        $themeid = $row['id'];
                        $fans = $data;
                        $fans['openid']=$item['openid'];
                        $qrimg = $qrcode;
                        $poster =  Poster::getByThemeIdnew($themeid,1);
                        if(!empty($poster['id'])){
                            $member = array(
                                "openid"   =>$fans['openid'],
                                'nickname' =>$fans['nickname'],
                                'avatar'   =>$fans['avatar'],
                                'themeid' =>$themeid,
                                'addtime' => TIMESTAMP,
                            );
                            $poster['bg']=str_replace("/99.jpg","/haibao.jpg",$poster['bg']);

                            $img = Poster::createGoodsPoster($poster, $member, $qrimg);
                            $hbimg = str_replace("http://", "https://", $img['img']) ;
                            db_update(t_worker, array('poster' =>$hbimg), array( 'themeid' => $themeid, 'openid' => $fans['openid']));
                        }
                    }
                }
            }
        }

		$data = array(
				'username' => trim($_P['username']),
				'nickname' => trim($_P['nickname']),
				'mobile' => trim($_P['mobile']),
				'avatar' => $avatar,
			);
		if(!empty($_P['openid'])) {
			db_update(t_fans, $data, array('openid' => $_P['openid']));
		}
		return_tips('更新成功','', 'success');
	}
}

if($op == 'display') {
    $gsum0 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_worker ) . "
            WHERE themeid ='{$themeid}' and mobile<>''" ));
    $gsum1 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_worker ) . "
            WHERE themeid ='{$themeid}' and level =1 and mobile<>''"));
    $gsum2 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_worker ) . "
            WHERE themeid ='{$themeid}' and level =2 and mobile<>''"));
    $gsum3 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_worker ) . "
            WHERE themeid ='{$themeid}' and level =3 and mobile<>''"));
    $gsum4 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_worker ) . "
            WHERE themeid ='{$themeid}' and team=0 and mobile<>''"));
    $gsum5 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_worker ) . "
            WHERE themeid ='{$themeid}' and (mobile='' or mobile is null)"));


	$themelist = Theme::getAllTheme();

	// if (empty($_P['createtime']['start'])){

	// 	$starttime =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
	// 	$starttime =  strtotime(date('Y-m-d 00:00:00',$starttime));
	// }else{
	// 	$starttime =  strtotime($_P['createtime']['start']);
	// }
 //    $endtime = empty($_P['createtime']['end']) ? strtotime(date('Y-m-d 23:59:59',TIMESTAMP)): strtotime($_P['createtime']['end']) ;
    

	$condition = ' w.themeid = :themeid';
	$params[':themeid'] = $themeid;
	
	if(!empty($_P['keyword'])){
		$condition .= ' and (w.nickname like :keyword or w.username like :keyword or w.mobile like :keyword)  ';
		$params[':keyword'] = '%'.$_P['keyword'].'%';
	}

	if(!empty($team_txt) && $team_txt!="请选择团队" && $team_txt!="请左侧选择商家"){
		$team=explode('|', $team_txt);
		$condition .= ' and w.team = :teamid';
		$params[':teamid'] = $team[0];
	}

	if(!empty($company_txt) && $company_txt!="请选择商家" ){
		$company=explode('|', $company_txt);
		$condition .= ' and w.company = :companyid';
		$params[':companyid'] = $company[0];
	}

	if(!isset($_P['status'])){
		$status = -1;
	}else{
		$status = intval($_P['status']);
	}
	if($status == 1 || $status == 2 || $status == 3){
		$condition .= ' and w.level = ' . $status ;
	}elseif ($status == 4){
		$condition .= ' and w.team=0' ;
	}
	if ($status == 5){
		$condition .= " and (w.mobile='' or w.mobile is null)"  ;
	}else{
		$condition .= " and w.mobile<>''"  ;
	}

    $gsum12 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
        WHERE r.themeid ='{$themeid}'  and r.status > 0 and r.status!=3" ));
    if ($config['joinfee']=='0.00' && $config['groupprice']=='0.00' && $gsum12==0){
        $freerecord = true;
    }else{
        $freerecord = false;
    }

    $paixu = $_P['paixu'];
    if ($paixu == 'forward') {
        $paixutxt = "order by forward desc,record desc";
    } elseif ($paixu == 'scansum') {
        $paixutxt = "order by scansum desc,record desc";
    }elseif ($paixu == 'newfans') {
        $paixutxt = "order by newfans desc,record desc";
    }elseif ($paixu == 'recordzx') {
        $paixutxt = "order by recordzx desc,record desc";
    } elseif ($paixu == 'recordxx') {
        $paixutxt = "order by recordxx desc,record desc";
    } elseif ($paixu == 'record') {
        $paixutxt = "order by record desc,recordxx desc";
    }else{
        $paixutxt = "order by w.level asc,w.uniacid,w.company,w.team,w.mobile";
    }

    $sql1 = "SELECT w.* , t.name as teamname,s.name as companyname, sum(r.newfans) as newfans,sum(r.record) as record,sum(r.recordxx) as recordxx,sum(r.recordzx) as recordzx,sum(r.fee) as fee,sum(r.scansum) as scansum,sum(r.forward) as forward FROM " . tablename ( t_worker ) . " w
        left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
		left join " . tablename ( t_team ) . " as t on w.team = t.id
		left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
        WHERE " . $condition  ;
    $sql2 = " group by w.uid " . $paixutxt. ",w.uid ";

	if(checksubmit('export_submit', true)){
		$list = db_select($sql1.$sql2, $params);
	}else{
	    $pageNumber = max ( 1, intval ( $_P['page'] ) );
	    $pageSize = 50;
	    $Limit  = " LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
	    $list = db_select($sql1.$sql2.$Limit, $params);
	}
	// $sql = 'SELECT w.*,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
	// 		left join " . tablename ( t_team ) . " as t on w.team = t.id
	// 		left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
	// 		WHERE " . $condition . "  ORDER BY level asc,uniacid,company,team,mobile  LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
	// $list = db_select($sql, $params);
	foreach ($list as $index =>$row){
		if (empty($row['mobile']) && empty($row['avatar'])) {
			$fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " 
			            WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['uid']));
			$list[$index]['nickname'] = $fans['nickname'];
			$list[$index]['avatar'] = $fans['avatar'];
		}
		$wlist[$index]['mobile']=mb_substr($row['mobile'],0,3,'utf-8').'*'.mb_substr($row['mobile'],0,-4,'utf-8');
	// 	if ($freerecord) {
	// 		$list[$index]['tj1'] = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
	// 			WHERE workerid = '{$row['uid']}' and themeid = '{$themeid}' " );
	// 		$list[$index]['tj2'] = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
	// 			WHERE fromuid = '{$row['uid']}' and themeid = '{$themeid}' and workerid = '{$row['uid']}'" );
	// 	}else{
	// 		$list[$index]['tj1'] = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
	// 			WHERE status > 0 and workerid = '{$row['uid']}' and themeid = '{$themeid}' " );
	// 		$list[$index]['tj2'] = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
	// 			WHERE status > 0 and fromuid = '{$row['uid']}' and themeid = '{$themeid}' and workerid = '{$row['uid']}'" );
	// 	}
		if($system['fenxiao']==1){
			$list[$index]['tj3'] = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_comm ) . "
					WHERE status = 1 and uid = '{$row['uid']}' and themeid = '{$themeid}' " );

			$list[$index]['tj4'] = db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
					WHERE status = 1 and uid = '{$row['uid']}' and themeid = '{$themeid}' " );

			$list[$index]['tj5'] = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_comm ) . "
					WHERE status = 0 and uid = '{$row['uid']}' and themeid = '{$themeid}' " );
		}
	// 	$list[$index]['newfans'] = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_fans ) . "
	// 			WHERE workerid = '{$row['uid']}' and themeid = '{$themeid}' " );
	}

	if(checksubmit('export_submit', true)){		
		$header = array();
		$header['uid'] = '员工ID';
		if ($system['ruanjian']==3) {
			$header['companyname']='公司';
		}
		$header['teamname']='团队';
		$header['nickname'] = '微信昵称';
		$header['username'] = '姓名';
		$header['mobile'] = '手机';
		$header['level']='身份';
		$header['forward']='转发';
		$header['scansum']='浏览';
		$header['newfans']='新粉丝';
		$header['record']='成交';
		$header['recordzx']='直销';
		$header['recordxx']='线下';
		if ($system['fenxiao']==1) {
			$header['tj4']='红包金额';
			$header['tj3']='红包收到';
			$header['tj5']='红包未发';
		}
		$header['addtime'] = '时间';	
		$keys = array_keys($header);
		$html = "\xEF\xBB\xBF";
		foreach ($header as $li) {
			$html .= $li . "\t ,";
		}
		$html .= "\n";
		if (!empty($list)) {
			foreach ($list as $row) {
				$row['nickname']=str_replace('"',"",$row['nickname']);
				$row['nickname']=str_replace(',',"",$row['nickname']);
				$row['username']=str_replace('"',"",$row['username']);
				$row['username']=str_replace(',',"",$row['username']);
				if($row['addtime'] > 0){
                    $row['addtime']  = date('Y-m-d H:i:s',$row['addtime']);
                } 
                $row['level'] = $shenfen[$row['level']];
				foreach ($keys as $key) {
					$data[] = $row[$key];
				}
				$user[] = implode("\t ,", $data) . "\t ,";
				unset($data);
			}
		}
		$html .= implode("\n", $user);
		header("Content-type:text/csv");
        header("Content-Disposition:attachment; filename=员工数据.csv");
        echo $html;
		exit();
	}

	$sql = 'SELECT count(w.id) FROM ' . tablename(t_worker) . " as w 
			left join " . tablename ( t_team ) . " as t on w.team = t.id
			left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
			WHERE " . $condition . " and w.mobile<>''";
    $total = db_fetchcolumn ($sql, $params);
	$pager = pagination ( $total, $pageNumber, $pageSize );

}






if($op == 'comm4status') {
	$status = intval($_P['status']);
	$state = db_update(t_worker, array('comm4status' => $status), array( 'id' => $id));
	return_tips('更改成功', '', 'success');
}


if($op == 'delete') {
	$uid = intval($_P['uid']);
	db_delete(t_worker, array('uid' => $uid));
	return_tips('删除成功', $url, 'success');
}

if($op == 'delete5') {
	db_query("DELETE FROM " . tablename ( t_worker ) ." WHERE mobile='' or mobile is null");
	return_tips('删除成功', $url, 'success');
}

$return_clicent = get_defined_vars();
return view('/worker' , $return_clicent);
}
}